import {
  addSysDictItem,
  editSysDictItem,
  selectAllSysDictType,
  selectDictItemByPage,
} from '@/api/information'
import {FormInstance} from 'ant-design-vue'
import {PropType} from 'vue'
import './components.less'
import ParamStandRange from '@/components/input/paramStandRange'
import {CoustomTableFn} from '@/components/table'

/**字典数据 状态数据 */
interface SysdictItems_state {
  /**字典类型列表 */
  sysdict_type_list: SysDict.Type[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: 'editItem' | 'addItem' | 'editParam' | null
    /**弹窗 标题*/
    title: string
    /** 字典数据 弹窗 修改 数据源 */
    edit_source: SysDict.Item | null
    /** 检测参数 弹窗 修改 数据源 */
    editParam_source: SysDict.EditItemDataSource | null
  }
  table: CTable<SysDict.Item>
  search: {
    dictTypeCode: string
    dictName: string
    dictCode: string
  }
}
let sysdictItems_state = reactive<SysdictItems_state>({
  sysdict_type_list: [],
  modal: {
    visible: false,
    type: null,
    title: '',
    edit_source: null,
    editParam_source: null,
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20,
    },
    onPaginatiChange({page, size}) {
      let {pagination} = toRefs(sysdictItems_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    },
    total: 0,
  },
  search: {
    dictTypeCode: '',
    dictName: '',
    dictCode: '',
  },
})

/**获取表格数据 */
export async function getTableDatas(data?: any) {
  let {
    dataSource,
    pagination,
    total: tableTotal,
    loading,
  } = toRefs(sysdictItems_state.table)
  let {search} = toRefs(sysdictItems_state)
  let defaultData = {
    page: pagination.value.page,
    size: pagination.value.size,
    dictTypeCode: search.value.dictTypeCode,
    dictName: search.value.dictName,
    dictCode: search.value.dictCode,
  }
  loading.value = true
  let res = await selectDictItemByPage(defaultData).catch(err => {})
  if (res) {
    let {list, total} = res.data
    dataSource.value = list
    tableTotal.value = total
  }
  loading.value = false
}

/**获取字典类型列表 */
export async function getSysdictTypeList() {
  let {sysdict_type_list} = toRefs(sysdictItems_state)
  let res = await selectAllSysDictType().catch(err => {})
  if (res) {
    sysdict_type_list.value = res.data.sort(
      (a, b) => Number(a.sort) - Number(b.sort)
    )
    console.log('类型列表', sysdict_type_list.value)
  }
}

/**字典数据 左侧 视窗主体 */
export const ViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup() {
    let {sysdict_type_list, search} = toRefs(sysdictItems_state)
    let {dictTypeCode} = toRefs(sysdictItems_state.search)
    onMounted(() => {
      getSysdictTypeList()
    })
    function handle_sysdictType_checked(data: string) {
      if (data === 'all') {
        dictTypeCode.value = ''
      } else {
        dictTypeCode.value = data
      }
      getTableDatas()
    }
    return () => (
      <div class="h-full viewLeftFilter overflow-y-auto pr-12">
        <label for="viewLeftFilter">
          <input
            type="radio"
            name="viewLeftFilter"
            id="viewLeftFilter"
            checked={search.value.dictTypeCode === ''}
            class="hidden input_acitve"
          ></input>
          <div
            class="viewLeftFilter-line   flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light"
            onClick={() => handle_sysdictType_checked('all')}
          >
            <div class="viewLeftFilter-icon w-1/12">
              <i class="iconfont"></i>
            </div>
            <div class="viewLeftFilter-label w-5/12">全部</div>
            <div class="viewLeftFilter-value w-5/12 flex justify-start items-center pr-1 text-info text-xs">
              <span class="truncate w-full text-right"> 查询所有类型</span>
            </div>
          </div>
        </label>
        {sysdict_type_list.value.map((type, idx) => (
          <label for={'viewLeftFilter' + idx}>
            <input
              type="radio"
              name="viewLeftFilter"
              id={'viewLeftFilter' + idx}
              checked={search.value.dictTypeCode === type.dictTypeCode}
              class="hidden input_acitve"
            ></input>
            <div
              class="viewLeftFilter-line flex justify-between items-center text-sm truncate cursor-pointer py-4 hover:bg-primary_light"
              onClick={() => handle_sysdictType_checked(type.dictTypeCode)}
            >
              <div class="viewLeftFilter-icon w-1/12">
                <i class="iconfont"></i>
              </div>
              <div class="viewLeftFilter-label w-5/12">{type.dictTypeName}</div>
              <div class="viewLeftFilter-value w-5/12 flex justify-start items-center pr-1 text-info text-xs ">
                <span class="truncate w-full text-right"> {type.dictDesc}</span>
              </div>
            </div>
          </label>
        ))}
      </div>
    )
  },
})

/**字典数据 左侧 头部 */
export const ViewLeftNav = defineComponent({
  name: 'ViewLeftNav',
  setup(props, {emit}) {
    let {search} = toRefs(sysdictItems_state)
    return () => (
      <div class="w-full h-full">
        {/* <a-input
          class="w-full h-full"
          placeholder="输入关键字进行过滤"
          defaultValue={search.value.dictName}
          v-model={[search.value.dictName, 'value']}
          onPressEnter={getTableDatas}
          allow-clear={true}
        ></a-input> */}
      </div>
    )
  },
})

/**字典数据 左侧 底部 */
export const ViewLeftFooter = defineComponent({
  name: 'ViewLeftFooter',
  setup(props, {emit}) {
    const handle_dictName_input_enter = () => {
      getTableDatas()
    }
    return () => (
      <div class="h-full px-4 flex justify-end items-center">
        <a-button
          class="ml-4"
          type="primary"
          onClick={handle_dictName_input_enter}
        >
          查询
        </a-button>
      </div>
    )
  },
})

/**字典数据 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<SysDict.Item>,
      default: {},
    },
  },
  setup(props) {
    let {visible, title, type, edit_source, editParam_source} = toRefs(
      sysdictItems_state.modal
    )
    const handle_type_edit_btn_click = () => {
      console.log(props.record)
      title.value = '修改字典数据'

      switch (props.record.dictTypeCode) {
        case '检测参数':
          type.value = 'editParam'
          editParam_source.value = props.record
          visible.value = true
          break
        default:
          type.value = 'editItem'
          edit_source.value = props.record
          visible.value = true
          break
      }
    }

    return () => (
      <div>
        <span
          class="mr-2 text-primary border-b cursor-pointer"
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
        {/* <span class="mr-2 text-primary border-b cursor-pointer">删除</span> */}
      </div>
    )
  },
})

/**字典数据 数据表格 */
// export const ItemTable = defineComponent({
//   setup(props) {
//     /**表格数据源 */
//     let {dataSource} = toRefs(sysdictItems_state.table)
//     type Key = string | number
//     /**表格头 */
//     let columns: AColum[] = [
//       {
//         title: '参考类型',
//         dataIndex: 'dictTypeCode',
//         ellipsis: true,
//       },
//       {
//         title: '数据名称',
//         dataIndex: 'dictName',
//         ellipsis: true,
//       },
//       {
//         title: '内容',
//         dataIndex: 'dictValue',
//         ellipsis: true,
//       },
//       {
//         title: '备注',
//         dataIndex: 'dictDesc',
//         ellipsis: true,
//       },
//       {
//         title: '状态',
//         dataIndex: 'status',
//         align: 'center',
//         ellipsis: true,
//       },
//       {
//         title: '创建时间',
//         dataIndex: 'createTime',
//         ellipsis: true,
//       },
//       {
//         title: '操作',
//         isUtil: true,
//         width: 140,
//       },
//     ]

//     /**处理表格头伸缩 */
//     function handleResizeColumn(w: any, col: any) {
//       console.log(w, col)

//       col.width = w
//     }
//     const state = reactive<{
//       selectedRowKeys: Key[]
//       loading: boolean
//     }>({
//       selectedRowKeys: [], // Check here to configure the default column
//       loading: false,
//     })
//     const onSelectChange = (selectedRowKeys: Key[], selectedRows: any) => {
//       state.selectedRowKeys = selectedRowKeys
//     }

//     return () => (
//       <a-table
//         dataSource={dataSource.value}
//         columns={columns}
//         rowKey={'id'}
//         pagination={false}
//         onResizeColumn={handleResizeColumn}
//         scroll={{
//           scrollToFirstRowOnChange: true,
//           y: 718,
//         }}
//         row-selection={{
//           selectedRowKeys: state.selectedRowKeys,
//           onChange: onSelectChange,
//         }}
//         customHeaderCell={(column: AColum[]) => {
//           return {
//             onClick: (e: any) => {
//               console.log(e)
//             },
//           }
//         }}
//       >
//         {{
//           bodyCell: ({
//             text,
//             record,
//             index,
//             column,
//           }: {
//             text: string
//             record: SysDict.Item
//             index: number
//             column: AColum
//           }) => {
//             if (column.isUtil) {
//               return <ItemHandleBtn record={record}></ItemHandleBtn>
//             } else {
//               return (
//                 <div class="truncate">
//                   <a-tooltip placement="top" title={text}>
//                     {text}
//                   </a-tooltip>
//                 </div>
//               )
//             }
//           },
//         }}
//       </a-table>
//     )
//   },
// })

// /**字典数据 分页控制 */
// export const ItemPagination = defineComponent({
//   setup() {
//     let {page, size} = toRefs(sysdictItems_state.table.pagination)
//     let {total} = toRefs(sysdictItems_state.table)
//     /**表格分页配置 */
//     let pagination = reactive({
//       current: page, //当前页数
//       pageSize: size,
//       defaultPageSize: size, //默认的每页条数
//       pageSizeOptions: [10, 20, 30, 50, 100], //指定每页可以显示多少条
//       total: total, //数据总数
//       hideOnSinglePage: false, //只有一页时是否隐藏分页器
//       showQuickJumper: true, //是否可以快速跳转至某页
//       showSizeChanger: true, //是否可以改变 pageSize
//       showTotal: (total: number, range: number[]) => {
//         return '共有' + total + '条'
//       }, //用于显示数据总量和当前数据顺序
//       size: 'small',
//       onChange: (page: number, pageSize: number) => {
//         sysdictItems_state.table.pagination_handle.change({
//           page,
//           size: pageSize,
//         })
//       },
//       onShowSizeChange: (current: number, size: number) => {
//         sysdictItems_state.table.pagination_handle.showSizeChange({
//           page: current,
//           size,
//         })
//       },
//     })
//     return () => (
//       <div class="h-mainViewfooter border-b border-default bg-white flex justify-start items-center pl-4">
//         <a-pagination
//           current={pagination.current}
//           page-size={pagination.pageSize}
//           total={pagination.total}
//           defaultPageSize={pagination.defaultPageSize}
//           pageSizeOptions={pagination.pageSizeOptions}
//           hideOnSinglePage={pagination.hideOnSinglePage}
//           showQuickJumper={pagination.showQuickJumper}
//           showSizeChanger={pagination.showSizeChanger}
//           showTotal={pagination.showTotal}
//           size={pagination.size}
//           onChange={pagination.onChange}
//           onShowSizeChange={pagination.onShowSizeChange}
//         ></a-pagination>
//       </div>
//     )
//   },
// })

const CoustomTable = CoustomTableFn<SysDict.Item>()
export const ItemTable = defineComponent({
  name: 'ItemTable',
  setup(props) {
    let {dataSource, loading, total, onPaginatiChange} = toRefs(
      sysdictItems_state.table
    )
    let {page, size} = toRefs(sysdictItems_state.table.pagination)

    let columns: CColumn<SysDict.Item>[] = [
      {
        title: '参考类型',
        dataIndex: 'dictTypeCode',
        width: 100,

        ellipsis: true,
      },
      {
        title: '数据代码',
        dataIndex: 'dictCode',
        width: 100,
        ellipsis: true,
      },
      {
        title: '数据名称',
        dataIndex: 'dictName',
        ellipsis: true,
      },
      {
        title: '内容',
        dataIndex: 'dictValue',
        ellipsis: true,
      },
      {
        title: '备注',
        dataIndex: 'dictDesc',
        ellipsis: true,
      },
      {
        title: '状态',
        dataIndex: 'status',
        align: 'center',
        ellipsis: true,
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        ellipsis: true,
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 140,
      },
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey="dictCode"
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value,
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
      >
        {{
          util: (record: SysDict.Item) => (
            <TypeHandleBtn record={record}></TypeHandleBtn>
          ),
        }}
      </CoustomTable>
    )
  },
})

/**字典数据 表单 添加用 */
const AddItemForm = defineComponent({
  emits: ['finish', 'cancel'],
  setup(props, {emit}) {
    let {sysdict_type_list, search} = toRefs(sysdictItems_state)
    let {dictTypeCode} = toRefs(sysdictItems_state.search)

    let formRef = ref<FormInstance>()
    let state = reactive<SysDict.AddItemDataSource>({
      dictDesc: '',
      dictName: '',
      dictTypeCode: dictTypeCode.value,
      dictValue: '',
    })

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      try {
        await addSysDictItem(state).catch(() => {})
        returnEmit()
      } catch (err) {
        console.error(err)
      }
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed')
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      formRef.value?.resetFields()

      emit('cancel')
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }

    const filterOption = (input: string, option: any) => {
      return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }

    onMounted(async () => {
      console.log('表单加载了')
      getSysdictTypeList()
    })
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name="addSysdictType"
        model={state}
        label-col={{span: 4}}
        wrapper-col={{span: 16}}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label="数据名称" name="dictName">
          <a-input v-model={[state.dictName, 'value']} />
        </a-form-item>
        <a-form-item label="内容" name="dictValue">
          <a-input v-model={[state.dictValue, 'value']} />
        </a-form-item>
        <a-form-item label="参考类型" name="dictTypeCode">
          <a-select
            v-model={[state.dictTypeCode, 'value']}
            show-search
            style="width: 200px"
            options={sysdict_type_list.value}
            filter-option={filterOption}
            fieldNames={{
              label: 'dictTypeName',
              value: 'dictTypeCode',
            }}
          ></a-select>
        </a-form-item>
        <a-form-item label="备注" name="dictDesc">
          <a-input v-model={[state.dictDesc, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="float-right mx-4" html-type="submit">
            提交
          </a-button>
          <a-button class="float-right mx-4" onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  },
})

/**字典数据 表单 修改用 */
const EditItemForm = defineComponent({
  emits: ['finish', 'cancel'],
  setup(props, {emit}) {
    let {edit_source} = toRefs(sysdictItems_state.modal)
    let formRef = ref<FormInstance>()
    let state = reactive<SysDict.EditItemDataSource>({
      dictDesc: edit_source.value?.dictDesc || '',
      dictName: edit_source.value?.dictName || '',
      dictCode: edit_source.value?.dictCode || '',
      dictValue: edit_source.value?.dictValue || '',
      sort: edit_source.value?.sort || '',
    })
    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      console.log(state)
      try {
        await editSysDictItem(state)
        returnEmit()
      } catch (err) {
        console.error(err)
      }
    }
    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed', state)
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      formRef.value?.resetFields()
      emit('cancel')
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }
    return () => (
      <a-form
        v-model={[formRef, 'ref']}
        name="editSysdictType"
        model={state}
        label-col={{span: 4}}
        wrapper-col={{span: 16}}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        <a-form-item label="数据名称" name="dictName">
          <a-input v-model={[state.dictName, 'value']} />
        </a-form-item>
        <a-form-item label="内容" name="dictValue">
          <a-input v-model={[state.dictValue, 'value']} />
        </a-form-item>
        <a-form-item label="备注" name="dictDesc">
          <a-input v-model={[state.dictDesc, 'value']} />
        </a-form-item>
        <a-form-item label="排序" name="sort">
          <a-input v-model={[state.sort, 'value']} />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" class="float-right mx-4" html-type="submit">
            提交
          </a-button>
          <a-button class="float-right mx-4" onClick={handle_form_cancel}>
            取消
          </a-button>
        </a-form-item>
      </a-form>
    )
  },
})

/**字典数据 表单 修改检测参数用 */
const EditParamForm = defineComponent({
  name: 'EditParamForm',
  emits: ['finish', 'cancel'],
  setup(props, {emit}) {
    let {editParam_source} = toRefs(sysdictItems_state.modal)
    let formRef = ref<FormInstance>()

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      try {
        if (!editParam_source.value) return
        await editSysDictItem(editParam_source.value).catch(err => {})
        returnEmit()
      } catch (err) {
        console.error(err)
      }
    }

    /**dictValue值变化 */
    const checkParamStandRangeChange = (value: string) => {
      if (!sysdictItems_state.modal.editParam_source) return
      let {dictValue} = toRefs(sysdictItems_state.modal.editParam_source)
      dictValue.value = value
    }

    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      returnEmit()
    }
    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      formRef.value?.resetFields()
      emit('cancel')
    }
    // 清空表单 关闭外层弹框
    const returnEmit = () => {
      formRef.value?.resetFields()
      emit('finish')
    }

    return () => {
      if (!editParam_source.value) return
      return (
        <a-form
          v-model={[formRef, 'ref']}
          name="editSysdictType"
          model={editParam_source.value}
          label-col={{span: 4}}
          wrapper-col={{span: 16}}
          onFinish={handle_form_finish}
          onFinishFailed={handle_form_finish_failed}
        >
          <a-form-item label="数据名称" name="dictName">
            <a-input v-model={[editParam_source.value.dictName, 'value']} />
          </a-form-item>
          <a-form-item label="内容" name="dictValue">
            <ParamStandRange
              defaultRange={editParam_source.value.dictValue}
              onChange={checkParamStandRangeChange}
            ></ParamStandRange>
          </a-form-item>
          <a-form-item label="备注" name="dictDesc">
            <a-input v-model={[editParam_source.value.dictDesc, 'value']} />
          </a-form-item>
          <a-form-item label="排序" name="sort">
            <a-input v-model={[editParam_source.value.sort, 'value']} />
          </a-form-item>
          <a-form-item>
            <a-button
              type="primary"
              class="float-right mx-4"
              html-type="submit"
            >
              提交
            </a-button>
            <a-button class="float-right mx-4" onClick={handle_form_cancel}>
              取消
            </a-button>
          </a-form-item>
        </a-form>
      )
    }
  },
})

/**字典数据 弹窗 */
export const ItemModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title} = toRefs(sysdictItems_state.modal)
    const handle_form_finish = () => {
      visible.value = false
      type.value = null
      getTableDatas()
    }
    const handle_form_cancel = () => {
      visible.value = false
      type.value = null
    }
    return () => {
      let dynamicCom
      switch (type.value) {
        case 'addItem':
          dynamicCom = (
            <AddItemForm
              onFinish={handle_form_finish}
              onCancel={handle_form_cancel}
            ></AddItemForm>
          )
          break
        case 'editItem':
          dynamicCom = (
            <EditItemForm
              onFinish={handle_form_finish}
              onCancel={handle_form_cancel}
            ></EditItemForm>
          )
          break
        case 'editParam':
          dynamicCom = (
            <EditParamForm
              onFinish={handle_form_finish}
              onCancel={handle_form_cancel}
            ></EditParamForm>
          )
          break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={handle_form_cancel}
        >
          {dynamicCom}
        </a-modal>
      )
    }
  },
})

/**字典数据 主体窗口 头部 操作栏 */
export const ItemMainViewNav = defineComponent({
  setup() {
    let {visible, title, type} = toRefs(sysdictItems_state.modal)
    const handle_add_btn_click = () => {
      visible.value = true
      type.value = 'addItem'
      title.value = '添加字典数据'
    }
    return () => (
      <div class="h-mainViewNav border-b border-default bg-white px-4 flex justify-start items-center">
        <a-button type="primary" onClick={handle_add_btn_click}>
          添加
        </a-button>
      </div>
    )
  },
})
